using System;
using System.Collections.Generic;
using System.Linq;

namespace LightPersist.Transactions
{
	public class TransactionGuard : IDisposable
	{
		readonly LightPersistContext _context;
		readonly Transaction _transaction;
		bool _isDisposed;

		internal TransactionGuard(LightPersistContext context, Transaction transaction)
		{
			if(context == null || transaction == null)
			{
				throw new ArgumentNullException();
			}
			_context = context;
			_transaction = transaction;
		}

		/// <summary>
		/// Sielently rollback
		/// </summary>
		public void Dispose()
		{
			if(!_isDisposed)
			{
				_isDisposed = true;
				if(_transaction.State.CanRollback())
				{
					_context.RollbackTransaction(_transaction);
				}
			}
		}

		public void CommitTransaction()
		{
			_context.CommitTransaction(_transaction);
		}

		public void RollbackTransaction()
		{
			_context.RollbackTransaction(_transaction);
		}

		public override string ToString()
		{
			return "Guard" + _transaction;
		}
	}
}